import fullscreenIcon from '@/assets/icons/safeCoGovernance/fullscreen.png'
import { CaretDownOutlined } from '@ant-design/icons'
import type { TreeSelectProps } from 'antd'
import { TreeSelect } from 'antd'
import classNames from 'classnames'
import { isEmpty } from 'lodash-es'
import { useEffect, useRef, useState } from 'react'
//头
import headerCentetBottomPng from '@/assets/icons/safeCoGovernance/header-center_bottom.png'
import headerCenterLeftPng from '@/assets/icons/safeCoGovernance/header_center_left.png'
import headerCenterRightPng from '@/assets/icons/safeCoGovernance/header_center_right.png'
import { useAppSelector } from '@/redux/store'
import { getRooteTree } from '@/utils/TreeUtils'

import RealTimeClock from '../../RealTimeClock'
import type { weatherRes } from '../../Weather'
import { Weather } from '../../Weather'
import { getChildAssociationList } from '../../data'
import type { AssociationData } from '../../interface'

import IconFont from '@/components/IconFontAl'
import './index.less'

interface WrapperHeaderProps {
  style?: React.CSSProperties
  selectedAssociationItem: AssociationData
  onAssociationClick: (newSelectedAssociationItem: AssociationData) => void
  weatherPlugin: any
  name?: string
  prevTitle: string
  nextTitle: string
  gotoNext: () => void
  gotoPrev: () => void
  isFullscreen: boolean
  onToggleFullScreen: () => void
}

const WrapperHeader: React.FC<WrapperHeaderProps> = (props) => {
  const {
    style,
    selectedAssociationItem,
    onAssociationClick,
    weatherPlugin,
    name,
    gotoNext,
    gotoPrev,
    prevTitle,
    nextTitle,
    isFullscreen,
    onToggleFullScreen
  } = props
  const { entId, operateEntFlag } = useAppSelector((state) => state.loginEnt)
  const [associationList, setAssociationList] = useState<
    TreeObj<AssociationData>[]
  >([])
  const [flatAssociationList, setFlatAssociationList] = useState<
    AssociationData[]
  >([])
  const [weather, setWeather] = useState<weatherRes>()

  //设置天气
  function _setReginCodeWeather(reginCode?: string) {
    let weatherRes: weatherRes
    if (!reginCode || !weatherPlugin) {
      setWeather(undefined)
      return
    }
    //查询实时天气信息, 查询的城市到行政级别的城市，如朝阳区、杭州市
    weatherPlugin.getLive(reginCode, (err: any, data: any) => {
      // console.log("杭州市-err", err)
      if (!err) {
        weatherRes = data
      }
      setWeather(weatherRes)
    })
  }

  //获取子级协会列表接口
  function _getChildAssociationList() {
    getChildAssociationList({ entId })
      .then((res) => {
        // console.log("--getChildAssociationList--res--:", res)
        const { data = [] } = res
        if (!isEmpty(data)) {
          const assList = data.map((dataItem) => ({
            key: dataItem.entId,
            label: dataItem.entName,
            regionCode: dataItem.regionCode,
            regionCodeValue: dataItem.regionCodeValue,
            operateEntFlag: dataItem.operateEntFlag
          }))

          setFlatAssociationList(assList)

          const newData = data.map((v) => {
            return {
              parentId: v.pid ?? '0',
              id: v.entId,
              title: v.entName,
              label: v.entName,
              key: v.entId,
              value: v.entId,
              ...v
            }
          })
          const list = getRooteTree('0', newData)

          setAssociationList(list)
        } else {
          setAssociationList([])
          setFlatAssociationList([])
        }
      })
      .catch((err) => {
        setAssociationList([])
        setFlatAssociationList([])
        console.error(
          '--BigScreenBase--WrapperHeader--getChildAssociationList--err--:',
          err
        )
      })
  }

  useEffect(() => {
    _getChildAssociationList() //协会列表
  }, [])

  useEffect(() => {
    _setReginCodeWeather(selectedAssociationItem.regionCode)
  }, [selectedAssociationItem.regionCode, weatherPlugin])

  //协会切换
  const associationClick: TreeSelectProps['onSelect'] = (key, node) => {
    if (selectedAssociationItem.key === key) return
    const associationItem = flatAssociationList.find((item) => item.key === key)
    if (!associationItem) {
      throw new Error('--切换协会时，未找到当前协会--')
    }
    onAssociationClick(associationItem)
  }

  const dropdownRef = useRef<HTMLDivElement>(null)

  return (
    <div className="wrapper-header-bigscreen" style={style}>
      <div className="header-time">
        <RealTimeClock />
      </div>
      <div className="header-center">
        <div className="center-left">
          <img className="z-img" src={headerCenterLeftPng} />
          <div className="z-arrow-title">
            <IconFont type="icon-xiangzuo" className="title-arrow" />
            <span className="title-text" onClick={gotoPrev}>
              {prevTitle}
            </span>
          </div>
        </div>
        <div
          className={classNames('center-title', {
            'no-child': !associationList[0]?.children
          })}
        >
          <p className="title-parent">
            {operateEntFlag === 'platform' && associationList.length > 0
              ? `${associationList[0].regionCodeValue ?? ''}交通${name}驾驶舱`
              : `${associationList[0]?.label ?? ''}交通${name}驾驶舱`}
          </p>
          {associationList.length > 0 && associationList[0].children && (
            <TreeSelect
              popupClassName="b-tree-dropdown"
              virtual={false}
              value={[selectedAssociationItem.key]}
              onChange={associationClick}
              variant="borderless"
              dropdownStyle={{
                // minWidth: "20%"
                width: 'max-content'
              }}
              listHeight={325}
              placement="bottomLeft"
              suffixIcon={
                <CaretDownOutlined
                  className="child-dropdown-icon"
                  onPointerEnterCapture={undefined}
                  onPointerLeaveCapture={undefined}
                />
              }
              treeDefaultExpandAll
              treeData={associationList}
              // getPopupContainer={(trigger) => trigger.current as HTMLElement}
            />
          )}

          <img className="title-bottom-img" src={headerCentetBottomPng} />
        </div>

        <div className="center-right">
          <img className="z-img" src={headerCenterRightPng} />
          <div className="z-arrow-title">
            <span className="title-text" onClick={gotoNext}>
              {nextTitle}
            </span>
            <IconFont type="icon-xiangyou" className="title-arrow" />
          </div>
        </div>
      </div>
      <div
        className="flexr  alc"
        style={{
          justifyContent: 'flex-end',
          width: 340
        }}
      >
        <div
          style={{
            visibility: isFullscreen ? 'hidden' : 'visible',
            display: 'flex',
            justifyContent: 'center',
            alignItems: 'center',
            cursor: 'pointer'
          }}
          onClick={() => {
            onToggleFullScreen()
          }}
        >
          <img src={fullscreenIcon} style={{ width: 32, height: 32 }} alt="" />

          <div
            style={{
              marginLeft: '8px',
              display: 'flex',
              justifyContent: 'center'
            }}
          >
            <span
              style={{
                color: 'rgba(255,255,255,0.6)',
                fontFamily: 'PuHuiTi-Regular'
              }}
            >
              展开全屏
            </span>
          </div>
        </div>
        <div
          style={{
            visibility: isFullscreen ? 'hidden' : 'visible',
            display: 'inline-block',
            background: 'rgba(255, 255, 255, 0.21)',
            width: 1,
            height: 34,
            margin: '0 16px'
          }}
        ></div>
        {selectedAssociationItem.regionCode ? (
          <Weather weather={weather} />
        ) : null}
      </div>
    </div>
  )
}

export default WrapperHeader
